/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */

#ifndef __PQ_TCPSocket_H__
#define __PQ_TCPSocket_H__

#include "PQNet.h"

namespace PQNet
{
	/*This class is used to wrap winsock tpc socket
	*/
	class TCPSocket
	{
	public:
		TCPSocket();
		TCPSocket(SOCKET socket);
		TCPSocket(std::string host, uint32 port);
		~TCPSocket();

		bool open();//open(create the socket)
		void close();

		bool connect(std::string host, uint32 port);
		bool connect();

		bool isSocketError() const;

		inline bool isValid()
		{
			return _socket!=INVALID_SOCKET;
		}

		inline SOCKET getSocketHandle()
		{
			return _socket;
		}

		bool bind(int port);
		bool listen(int backlog=5);
		

		SOCKET accept( struct sockaddr* addr, int* addrlen);

		//socket io control
		bool setReuseAddr(bool on=true);
		bool setNonBlocking(bool on=true);

		int getLinger() const;
		bool setLinger(int time);

		inline SOCKADDR_IN getSocketAddr()
		{
			return _socketAddr;
		}

		// receive data from peer
		int receive(void* buf, int len, int flags = 0);

		/*Get amount of data in socket input buffer
		@return amount of data in socket input buffer.
		*/
		int available() const;
	protected:
		bool _opened;
		SOCKET _socket;//win socket handle
		SOCKADDR_IN _socketAddr;	//win socket address
		
		std::string _hostAddr;// peer host
		uint32 _port;// peer port

	};
}

#endif

